package maths

import (
	"fmt"
	"github.com/shopspring/decimal"
	"strconv"
)

// 保留2位小数
func Decimal2Bit(value float64) float64 {
	data, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", value), 2)
	return data
}

// 保留4位小数
func Decimal4Bit(value float64) float64 {
	data, _ := strconv.ParseFloat(fmt.Sprintf("%.4f", value), 4)
	return data
}

// 保留6位小数
func Decimal6Bit(value float64) float64 {
	data, _ := strconv.ParseFloat(fmt.Sprintf("%.6f", value), 6)
	return data
}

// 相乘
func DecimalMul(dec1, dec2 string) (string, error) {
	n1, err := decimal.NewFromString(dec1)
	if err != nil {
		return "", err
	}
	n2, err := decimal.NewFromString(dec2)
	if err != nil {
		return "", err
	}
	return n1.Mul(n2).String(), nil
}

//相加
func DecimalAdd(dec1, dec2 string) (string, error) {
	n1, err := decimal.NewFromString(dec1)
	if err != nil {
		return "", err
	}
	n2, err := decimal.NewFromString(dec2)
	if err != nil {
		return "", err
	}
	return n1.Add(n2).String(), nil
}

//相除
func DecimalDiv(dec1, dec2 string) (string, error) {
	n1, err := decimal.NewFromString(dec1)
	if err != nil {
		return "", err
	}
	n2, err := decimal.NewFromString(dec2)
	if err != nil {
		return "", err
	}
	return n1.Div(n2).String(), nil
}

//相减
func DecimalSub(dec1, dec2 string) (string, error) {
	n1, err := decimal.NewFromString(dec1)
	if err != nil {
		return "", err
	}
	n2, err := decimal.NewFromString("-" + dec2)
	if err != nil {
		return "", err
	}
	return n1.Add(n2).String(), nil
}
